const OTA_CTRIP = "trip";

function formatDate(date, format) {
  const map = {
    Y: date.getFullYear(),
    y: String(date.getFullYear()).slice(-2),
    M: date.getMonth() + 1,
    D: date.getDate(),
    H: date.getHours(),
    h: date.getHours() % 12 || 12,
    m: date.getMinutes(),
    s: date.getSeconds(),
    S: date.getMilliseconds(),
    A: date.getHours() >= 12 ? "PM" : "AM",
    a: date.getHours() >= 12 ? "pm" : "am",
  };

  return format.replace(/Y+|y+|M+|D+|H+|h+|m+|s+|S+|A+|a+/g, (match) => {
    const key = match[0];
    const length = match.length;
    const value = String(map[key]);

    if (key === "Y" || key === "y") {
      return length === 2 ? value.slice(-2) : value;
    }

    return value.padStart(length, "0");
  });
}

function getPageId() {
  const item =
    localStorage.getItem("UBT_BFA") ||
    localStorage.getItem("UBT_LASTVIEW") ||
    localStorage.getItem("click_track");

  if (item) {
    return JSON.parse(item).pageId;
  }

  return "";
}

function getOrderDetail(order) {
  const params = {
    orderKey: null,
    formID: order.FormID,
    token: order.Token,
    sourceType: "Ebooking",
    ctripOrderSourceType: "EBK",
    hotel: order.Hotel,
    ignoreReadLog: false,
    orderID: order.OrderID,
    hoteluuidkeys: "",
    pageIdx: 1,
  };

  window.tl.xAjax({
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(params),
    type: "POST",
    url: "/ebkorderv2/api/order/domestic/orderDetail",
    error: () => {
      console.log("error");
    },
    success: (result) => {
      const { data } = result;
      window.postMessage({
        msgType: "response",
        ota: OTA_CTRIP,
        data: [data],
      });
    },
  });
}

async function fetchOrderList(params) {
  return new Promise((resolve, reject) => {
    window.tl.xAjax({
      contentType: "application/json; charset=utf-8",
      data: JSON.stringify(params),
      type: "POST",
      url: "/ebkorderv2/api/order/domestic/allOrderList",
      error: () => {
        console.log("error");
        reject();
      },
      success: async (result) => {
        const orders = result?.data?.orders;

        if (orders?.length) {
          for (const order of orders) {
            getOrderDetail(order);

            await sleep(3000 + Math.random() * 2000);
          }
        }

        resolve();
      },
    });
  });
}

async function getUnCheckInOrderList() {
  const date = new Date();
  const dateStart = formatDate(date, "YYYY-MM-DD");
  const dateEnd = dateStart;

  const params = {
    customFilter: "UnCheckIn",
    dateType: "ALL",
    dateStart,
    dateEnd,
    orderType: "ALL",
    orderStatus: "0",
    orderID: "",
    clientName: "",
    bookingNo: "",
    roomName: "",
    confirmName: "",
    isGuarantee: false,
    isPP: false,
    isFG: false,
    isUrgent: false,
    isCreditOrder: false,
    receiveType: "",
    isHoldRoom: false,
    isFreeSale: false,
    sourceType: "Ebooking",
    AllinanceName: "",
    UnBookingInvoice: false,
    IsBookingInvoice: false,
    GuestComplaintsStatus: null,
    OrderFAQStatus: null,
    isUnionMember: false,
    showSupplierOrderCount: false,
    showCTOrderCount: false,
    showOfficialOrderCount: false,
    ClientDateTime: formatDate(date, "YYYY-MM-DD HH:mm:ss"),
    DayOffSetType: -999,
    RoomTicketOrder: null,
    IsImComfirmOrder: null,
    IsFreeRoomOrder: false,
    IsXcsmz: null,
    pageInfo: {
      pageIndex: 1,
      orderBy: "ArrivalDate",
    },
    searchAllHotel: false,
    loadFirstDetail: true,
    formOrderModule: true,
    pageId: getPageId(),
    pageIdx: 1,
  };

  await fetchOrderList(params);
}

async function getCancelOrderList() {
  const date = new Date();
  const dateStart = formatDate(date, "YYYY-MM-DD");
  const dateEnd = formatDate(
    new Date(Date.now() - 30 * 24 * 3600 * 1000),
    "YYYY-MM-DD",
  );

  const params = {
    customFilter: "None",
    dateType: "ALL",
    dateStart: dateStart,
    dateEnd: dateEnd,
    orderType: "C",
    orderStatus: "0",
    orderID: "",
    clientName: "",
    bookingNo: "",
    roomName: "",
    confirmName: "",
    isGuarantee: false,
    isPP: false,
    isFG: false,
    isUrgent: false,
    isCreditOrder: false,
    receiveType: "",
    isHoldRoom: false,
    isFreeSale: false,
    sourceType: "Ebooking",
    AllinanceName: "",
    UnBookingInvoice: false,
    IsBookingInvoice: false,
    GuestComplaintsStatus: null,
    OrderFAQStatus: null,
    isUnionMember: false,
    showSupplierOrderCount: false,
    showCTOrderCount: false,
    showOfficialOrderCount: false,
    ClientDateTime: formatDate(date, "YYYY-MM-DD HH:mm:ss"),
    DayOffSetType: -999,
    RoomTicketOrder: null,
    IsImComfirmOrder: null,
    IsFreeRoomOrder: false,
    IsXcsmz: null,
    pageInfo: {
      pageIndex: 1,
      orderBy: "FormDate",
    },
    searchAllHotel: false,
    loadFirstDetail: true,
    formOrderModule: true,
    pageId: getPageId(),
    pageIdx: 1,
  };

  await fetchOrderList(params);
}

window.addEventListener("message", async (event) => {
  const { data } = event;

  if (!data) {
    return;
  }

  const msgType = data.msgType;

  if (msgType === PULL_CTRIP) {
    await getUnCheckInOrderList();
    await getCancelOrderList();
  }
});
